package org.uned.agonzalo16.bitacora.web.message;

import java.util.Date;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.uned.agonzalo16.bitacora.dao.MessageDao;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.Message;
import org.uned.agonzalo16.bitacora.domain.User;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;

@RequestMapping("/message")
@Controller
@SessionAttributes({ "userAttribute" })
public class MessageController {

	@Autowired
	private UserDao userDao;

	@Autowired
	private MessageDao messageDao;

	@RequestMapping(method = RequestMethod.GET, value = "/listReceive")
	public String listReceive(Model model, @ModelAttribute("userAttribute") AuthenticatedUser user) {

		User authUser = userDao.get(user.getId());

		model.addAttribute("receive", messageDao.findByDestination(authUser));

		return "message/listReceive";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/listSend")
	public String listSend(Model model, @ModelAttribute("userAttribute") AuthenticatedUser user) {

		User authUser = userDao.get(user.getId());

		model.addAttribute("msgs", messageDao.findByOrigin(authUser));

		return "message/listSend";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/show/{id}")
	public String show(@PathVariable("id") Long id, Model model, @ModelAttribute("userAttribute") AuthenticatedUser user) {
		User authUser = userDao.get(user.getId());
		Message msg = messageDao.get(id);
		model.addAttribute("message", msg);
		model.addAttribute("reply", !msg.getOrigin().equals(authUser));

		if (!msg.getRead() && msg.getDestination().equals(authUser)) {
			msg.setRead(true);
			messageDao.merge(msg);
		}

		return "message/show";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/beginCreate")
	public String beginCreate(Model model) {
		model.addAttribute("message", new MessageForm());
		return "message/create";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/create")
	public String create(@Valid @ModelAttribute("message") MessageForm form, BindingResult result, @ModelAttribute("userAttribute") AuthenticatedUser user) {

		if (result.hasErrors()) {
			return "message/create";
		}

		// validar que el destino existe
		User destination = userDao.findByUsername(form.getDestination());
		if (destination == null) {
			result.rejectValue("destination", "invalidusername", "invalidusername");
			return "message/create";
		}

		Message msg = new Message();
		msg.setCreationDate(new Date());
		msg.setSubject(form.getSubject());
		msg.setContent(form.getContent());
		msg.setOrigin(userDao.get(user.getId()));
		msg.setDestination(destination);

		messageDao.merge(msg);

		return "redirect:/message/listReceive";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/reply/{id}")
	public String reply(@PathVariable("id") Long id, Model model) {
		MessageForm form = new MessageForm();
		Message msg = messageDao.get(id);
		form.setSubject("[RE] " + msg.getSubject());
		form.setDestination(msg.getOrigin().getUsername());

		model.addAttribute("message", form);
		return "message/create";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/delete")
	public String delete(@RequestParam("id") Long id, @ModelAttribute("userAttribute") AuthenticatedUser user) {

		Message msg = messageDao.get(id);

		if (msg.getOrigin().getId().equals(user.getId())) {
			msg.setDeletedByOrigin(true);
		}

		if (msg.getDestination().getId().equals(user.getId())) {
			msg.setDeletedByDestination(true);
		}

		if (msg.getDeletedByDestination() && msg.getDeletedByOrigin()) {
			messageDao.delete(id);
		} else {
			messageDao.merge(msg);
		}

		return "redirect:/message/listReceive";
	}

}
